package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.DataCatBiz;
import com.useeinfo.oa.modules.base.biz.FacilityBiz;
import com.useeinfo.oa.modules.base.biz.FacilityDataBiz;
import com.useeinfo.oa.modules.base.biz.ResourceBiz;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.logger.biz.FacilityDataLogBiz;
import com.useeinfo.oa.modules.logger.entity.FacilityDataLog;
import com.useeinfo.oa.modules.logger.enums.LogTypeEnum;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @auther: bin.liu
 * @Date: 2018/12/13 10:24
 * @Description: 设备资料action
 */
@Controller
@RequestMapping("/web/admin/facilityData")
public class FacilityDataManageAction {

    @Autowired
    private FacilityDataBiz facilityDataBiz;

    @Autowired
    private ResourceBiz resourceBiz;

    @Autowired
    private FacilityBiz facilityBiz;

    @Autowired
    private DataCatBiz dataCatBiz;

    @Autowired
    private FacilityDataLogBiz facilityDataLogBiz;

    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/facilityData/facilityDataList");
        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "facilityName", required = false) String facilityName,
                               @RequestParam(value = "dataCatName", required = false) String dataCatName,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                                HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("facilityName", facilityName);
        queryParam.getSqlMap().put("dataCatName", dataCatName);
        if (StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        return facilityDataBiz.findJSONList(queryParam);
    }


    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id,HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        FacilityData facilityData = facilityDataBiz.findModel(StringConverters.ToLong(id));
        modelAndView.addObject("facilityData",facilityData);
        JSONArray dataCatIds=new JSONArray();
        JSONArray facilityIds = new JSONArray();
        String filePath = "";
        String fileName = "";
        if (facilityData != null) {
            facilityData.getDataCatSet().forEach(dataCat -> dataCatIds.add(dataCat.getId()));
            facilityData.getFacilitySet().forEach(facility -> facilityIds.add(facility.getId()));
            if (facilityData.getResourceSet() != null && facilityData.getResourceSet().size() != 0) {
                List<Resource> resourceList = new ArrayList<>(facilityData.getResourceSet());
                String hostPath = Configuration.getConfigurationByName("hostUrl");
                hostPath += hostPath.endsWith("/") ? "" : "/";
                filePath = hostPath + resourceList.get(0).getPath();
                fileName = resourceList.get(0).getResourceName();
            }
        }
        modelAndView.addObject("dataCatIds",dataCatIds);
        modelAndView.addObject("facilityIds",facilityIds);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise",enterprise);
        modelAndView.addObject("filePath", filePath);
        modelAndView.addObject("fileName", fileName);
        modelAndView.setViewName("pages/admin/facilityData/facilityDataEdit");

        return modelAndView;
    }

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(FacilityData facilityData) {
        facilityDataBiz.addOrUpdate(facilityData);
        return ResultUtil.success();
    }


    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeFacilityDataEdit")
    @ResponseBody
    public ResultDto executeFacilityDataEdit(FacilityData facilityData,
                                         @RequestParam(value = "createDate1", required = false) String createDate,
                                         @RequestParam(value = "facilityDataName", required = false) String facilityDataName,
                                         @RequestParam(value = "description", required = false) String description,
                                         @RequestParam(value = "selectFacilityId[]", required = false) List<String> selectFacilityIds,
                                         @RequestParam(value = "selectDataCatId[]", required = false) List<String> selectDataCatIds,
                                         @RequestParam(value = "sImg1", required = false) String sImg1,
                                         @RequestParam(value = "pic1", required = false) MultipartFile pic1,
                                         HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        if (facilityDataBiz.existFacilityData(facilityData,enterprise.getId())) {
            return ResultUtil.error("您输入的设备资料名称为空或已存在，请重新输入");
        }
        if (StringUtils.isNotBlank(createDate)) {
            facilityData.setCreateDate(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", createDate));
        }
        if (facilityData.getId() == null) {
            facilityData.setSerialNum(facilityDataBiz.getSerialNum(enterprise.getId()+""));
        }
        if (CollectionUtils.isNotEmpty(selectFacilityIds)) {
            Set<Facility> facilitySet = new HashSet<>();
            List<Facility> facilityList = facilityBiz.findModeIn(selectFacilityIds);
            for (Facility facility : facilityList) {
                facilitySet.add(facility);
            }
            facilityData.setFacilitySet(facilitySet);
        }
        if (CollectionUtils.isNotEmpty(selectDataCatIds)) {
            Set<DataCat> dataCatSet = new HashSet<>();
            List<DataCat> dataCatList = dataCatBiz.findModeIn(selectDataCatIds);
            for (DataCat dataCat : dataCatList) {
                dataCatSet.add(dataCat);
            }
            facilityData.setDataCatSet(dataCatSet);
        }

        //上传资料操作
        if ("1".equals(sImg1)) {
            //首先删除之前的关联资料文件
            facilityData.setResourceSet(null);
            //如果有新资料文件 再存新资料文件
            String savePath1 = FileUtils.fileUpload(pic1, ConstantKeyFilePath.FACILITY_DATA_PDF_DIR, ConstantKeyFilePath.FACILITY_DATA_PDF_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            if (StringUtils.isNotEmpty(savePath1)) {
                Resource resource = new Resource();
                String resourceName = pic1.getOriginalFilename();
                resource.setPath(savePath1);
                resource.setResourceName(resourceName);
                resource.setResourceTypeEnum(ResourceTypeEnum.PDF);
                resourceBiz.addOrUpdate(resource);
                Set<Resource> resourceSet = new HashSet<>();
                resourceSet.add(resource);
                facilityData.setResourceSet(resourceSet);
            }
        } else {
            if (facilityData.getId() != null) {
                facilityData.setResourceSet(facilityDataBiz.findModel(facilityData.getId()).getResourceSet());
            }
        }
        facilityData.setEnterprise(enterprise);
        // 添加资料操作日志
        FacilityDataLog facilityDataLog = new FacilityDataLog();
        if (facilityData.getId() == null) {
            facilityDataLog.setLogTypeEnum(LogTypeEnum.insert);
            facilityDataLog.setContent("新增资料：" + facilityData.getFacilityDataName());
        } else {
            facilityDataLog.setLogTypeEnum(LogTypeEnum.update);
            facilityDataLog.setContent("修改资料：" + facilityData.getFacilityDataName());
        }
        facilityDataLog.setUserId(systemUser.getId());
        facilityDataLog.setUserName(systemUser.getUserName());
        facilityDataLog.setUserIp(request.getRemoteAddr());
        facilityDataLog.setEnterpriseId(enterprise.getId());
        facilityDataBiz.addOrUpdate(facilityData);
        facilityDataLog.setFacilityDataId(facilityData.getId());
        facilityDataLog.setFacilityDataName(facilityData.getFacilityDataName());
        facilityDataLogBiz.addOrUpdate(facilityDataLog);

        return ResultUtil.success();
    }

    /**
     * 逻辑删除设备资料信息
     */
    @RequestMapping("/logicRemoveFacilityData")
    @ResponseBody
    public ResultDto logicRemoveFacilityGroup(@RequestParam(value = "id", required = false) String idParam,
                                              HttpServletRequest request) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        FacilityData facilityData = facilityDataBiz.findModel(StringConverters.ToLong(idParam));
        if (facilityData == null) {
            return ResultUtil.error("无此资料");
        }
        // 添加资料操作日志
        FacilityDataLog facilityDataLog = new FacilityDataLog();
        facilityDataLog.setLogTypeEnum(LogTypeEnum.delete);
        facilityDataLog.setContent("删除资料：" + facilityData.getFacilityDataName());
        facilityDataLog.setUserId(systemUser.getId());
        facilityDataLog.setUserName(systemUser.getUserName());
        facilityDataLog.setUserIp(request.getRemoteAddr());
        facilityDataLog.setEnterpriseId(enterprise.getId());
        facilityDataLog.setFacilityDataId(StringConverters.ToLong(idParam));
        facilityDataLog.setFacilityDataName(facilityData.getFacilityDataName());
        facilityDataLogBiz.addOrUpdate(facilityDataLog);
        Long id = StringConverters.ToLong(idParam);
        facilityDataBiz.delete(id);
        return ResultUtil.success();
    }

    /**
     * 预览资料pdf文件信息
     */
    @RequestMapping("/previewFacilityDataFile")
    @ResponseBody
    public ModelAndView previewFacilityDataFile(@RequestParam(value = "id", required = false) String id) {
        ModelAndView modelAndView = new ModelAndView();
        FacilityData facilityData = facilityDataBiz.findModel(StringConverters.ToLong(id));
        String filePath = "";
        String fileName = "";
        if (facilityData != null) {
            if (facilityData.getResourceSet() != null && facilityData.getResourceSet().size() != 0) {
                List<Resource> resourceList = new ArrayList<>(facilityData.getResourceSet());
                String hostPath = Configuration.getConfigurationByName("hostUrl");
                hostPath += hostPath.endsWith("/") ? "" : "/";
                filePath = hostPath + resourceList.get(0).getPath();
                fileName = resourceList.get(0).getResourceName();
            }
        }
        modelAndView.addObject("filePath", filePath);
        modelAndView.addObject("fileName", fileName);
        modelAndView.setViewName("pages/admin/facilityData/previewFile");
        return modelAndView;
    }
}
